;
(function() {

    var currentConnection = null;
    var deletingConnection = null;

    function getRealIdFromFake(fakeId) {
        var tokens = fakeId.split("-");
        return tokens.pop();
    }

    /* Prende in input una stringa tipo #FFFFFF o FFFFFF e ritorna un oggetto cha ha proprietà rbg decimali
     * 
     * @param {String} hex
     * @returns Una struttura con proprietà r, g, b. Ognuna rappresentante la proprietà del colore.
     */
    function hexToRgb(hex) {
        // nel caso venga passato il cancelletto lo elimina dalla stringa
        hex.replace("#", "");
        // Espande la forma a triplete (tipo "03F") nella forma estesa (analogamente "0033FF")
        var shorthandRegex = /^#?([a-f\d])([a-f\d])([a-f\d])$/i;
        hex = hex.replace(shorthandRegex, function(m, r, g, b) {
            return r + r + g + g + b + b;
        });

        var result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
        return result ? {
            r: parseInt(result[1], 16),
            g: parseInt(result[2], 16),
            b: parseInt(result[3], 16)
        } : null;
    }
    /* Traduce un componente decimale in HEX
     * 
     * @param {String} c
     * @returns {String}
     */
    function componentToHex(c) {
        var hex = c.toString(16);
        return hex.length == 1 ? "0" + hex : hex;
    }

    /* Prende in input i valori RGB e ritorna una stringa in esadecimale tipo #FFFFFF
     * 
     * @param {String} r
     * @param {String} g
     * @param {String} b
     * @returns {String} tipo #FFFFFF
     */
    function rgbToHex(r, g, b) {
        return "#" + componentToHex(r) + componentToHex(g) + componentToHex(b);
    }

    connections = [],
            updateConnections = function(conn) {
        // metto in un array globale

        if (connections.length > 0) {
            //connections = connections.sort();
            console.log("Connection NON VUOTO");
            for (var j = 0; j < connections.length; j++) {
                console.log("check connessione ", connections[j].id);
                if ((conn.sourceId === connections[j].sourceId && conn.targetId === connections[j].targetId) ||
                        (conn.sourceId === connections[j].targetId && conn.targetId === connections[j].sourceId)) {
                    //console.log("Trovate connessioni uguali "+connections[j].id,+" - "+connections[j+1].id);
                    //results.push(connections[j]);
                    return false;
                }

            }
            console.log("Aggiornata lista connessioni: ", conn.id);
            connections.push(conn);


        } else {
            console.log("Connection VUOTO");
            console.log("Aggiornata lista connessioni: ", conn.id);
            connections.push(conn);
        }
        // aggiunta cosa db
        return true;
    };

    $("#color-confirm").click(function() {
        var realSourceId = getRealIdFromFake(currentConnection.sourceId);
        var realTargetId = getRealIdFromFake(currentConnection.targetId);
        var decimalColor = hexToRgb($("#currentColor").val());

        currentConnection.getOverlay("label").setLabel(decimalColor.r + ", " + decimalColor.g + ", " + decimalColor.b);

        $.post("/connectionsServlet", {
            startPlanet: realSourceId,
            endPlanet: realTargetId,
            actionToDo: "insert",
            red: decimalColor.r,
            green: decimalColor.g, 
            blue: decimalColor.b
        }).done(function(data) {
            alert("Connessione tra "+realSourceId + " e " + realTargetId + " inserita con colore " + decimalColor.r + ", " + decimalColor.g + ", " + decimalColor.b);
        });
 
    });
    $("#color-cancel").click(function() {
        var realSourceId = getRealIdFromFake(currentConnection.sourceId);
        var realTargetId = getRealIdFromFake(currentConnection.targetId);

        $.post("/connectionsServlet", {
            startPlanet: realSourceId,
            endPlanet: realTargetId,
            actionToDo: "insert",
            red: 255,
            green: 255, 
            blue: 255
        }).done(function(data) {
            alert("Connessione tra "+realSourceId + " e " + realTargetId + " inserita senza colore ");
        });
    });
    
    

    window.jsPlumbDemo = {
        init: function() {

            jsPlumb.importDefaults({
                // default drag options
                DragOptions: {cursor: 'pointer', zIndex: 2000},
                // default to blue at one end and green at the other
                EndpointStyles: [{fillStyle: '#558822'}],
                // blue endpoints 7 px; green endpoints 11.
                Endpoints: [["Dot", {radius: 11}]],
                // the overlays to decorate each connection with.  note that the label overlay uses a function to generate the label text; in this
                // case it returns the 'labelText' member that we set on each connection in the 'init' method below.
                ConnectionOverlays: [
                    //[ "Arrow", { location:0.9 } ],
                    ["Label", {
                            location: 0.5,
                            id: "label",
                            cssClass: "aLabel"
                        }]
                ]
            });

            // this is the paint style for the connecting lines..
            var whiteColor = "rgba(255,255,255,0.5)";
            var redColor = "rgba(255, 165, 0,0.5)";
            var transparent = "rgba(0, 0, 0,0)";
            var connectorPaintStyle = {
                lineWidth: 3,
                strokeStyle: whiteColor,
                joinstyle: "round",
                //outlineColor:transparent,
                //outlineWidth:7
            },
                    // .. and this is the hover style. 
                    connectorHoverStyle = {
                lineWidth: 3,
                strokeStyle: redColor
            },
            // the definition of source endpoints (the small blue ones)
            sourceEndpoint = {
                endpoint: "Dot",
                paintStyle: {fillStyle: whiteColor, radius: 15},
                isSource: true,
                isTarget: true,
                connector: ["Straight", /*{ stub:[40, 60], gap:10 }*/],
                connectorStyle: connectorPaintStyle,
                //hoverPaintStyle:connectorHoverStyle,
                connectorHoverStyle: connectorHoverStyle,
                dragOptions: {},
                beforeDrop: function(params) {
                    return updateConnections(params.connection);
                },
                maxConnections: -1
            },
            // a source endpoint that sits at BottomCenter
            //	bottomSource = jsPlumb.extend( { anchor:"BottomCenter" }, sourceEndpoint),
            // the definition of target endpoints (will appear when the user drags a connection) 
            targetEndpoint = {
                endpoint: "Dot",
                paintStyle: {fillStyle: "#558822", radius: 11},
                hoverPaintStyle: connectorHoverStyle,
                maxConnections: -1,
                dropOptions: {hoverClass: "hover", activeClass: "activeConn"},
                isTarget: true,
                overlays: [
                    ["Label", {location: [0.5, -0.5], label: "Drop", cssClass: "endpointTargetLabel"}]
                ]
            };
            // init = function(connection) {



            // var text = prompt("Ragione connessione",connection.id);
            // if(text == null){
            // text = "";
            // connection.getOverlay("label").hide();
            // } 
            // connection.getOverlay("label").setLabel(text);
// 				
            // connection.bind("editCompleted", function(o) {
            // if (typeof console != "undefined")
            // console.log("connection edited. path is now ", o.path);
            // });


            // };			

            var allSourceEndpoints = [];
            _addEndpoints = function(toId, sourceAnchors, targetAnchors) {
                for (var i = 0; i < sourceAnchors.length; i++) {
                    var sourceUUID = toId + sourceAnchors[i];
                    allSourceEndpoints.push(jsPlumb.addEndpoint(toId, sourceEndpoint, {anchor: sourceAnchors[i], uuid: sourceUUID}));
                }
                /*
                 for (var j = 0; j < targetAnchors.length; j++) {
                 var targetUUID = toId + targetAnchors[j];
                 allTargetEndpoints.push(jsPlumb.addEndpoint(toId, targetEndpoint, { anchor:targetAnchors[j], uuid:targetUUID }));						
                 }*/
            };


//            _addEndpoints("endpoint-36", ["TopCenter"]);

            // listen for new connections; initialise them the same way we initialise the connections at startup.
            jsPlumb.bind("jsPlumbConnection", function(connInfo, originalEvent) {
                init(connInfo.connection);
            });

            // make all the window divs draggable						
            jsPlumb.draggable(jsPlumb.getSelector(".window"), {
                stop: function() {
                    var planetId = getRealIdFromFake($(this).attr("id"));
                    var x = $(this).css("left").replace("px", "");
                    var y = $(this).css("top").replace("px", "");

                    $.post("/connectionsServlet", {
                        planetMoved: planetId,
                        setX: x,
                        setY: y
                    }).done(function(data) {
                        alert("Aggiornata posizione sul db di: " + planetId + " con punto " + x + ", " + y);
                    });
                }
            });
            // THIS DEMO ONLY USES getSelector FOR CONVENIENCE. Use your library's appropriate selector method!
            //jsPlumb.draggable(jsPlumb.getSelector(".window"));


            // Connessioni programmatiche
            /*jsPlumb.connect({uuids:["window2BottomCenter", "window3TopCenter"], editable:true});
             jsPlumb.connect({uuids:["window2LeftMiddle", "window4LeftMiddle"], editable:true});
             jsPlumb.connect({uuids:["window4TopCenter", "window4RightMiddle"], editable:true});
             jsPlumb.connect({uuids:["window3RightMiddle", "window2RightMiddle"], editable:true});
             jsPlumb.connect({uuids:["window4BottomCenter", "window1TopCenter"], editable:true});
             jsPlumb.connect({uuids:["window3BottomCenter", "window1BottomCenter"], editable:true});*/
            //

            //
            // listen for clicks on connections, and offer to delete connections on click.
            //
            jsPlumb.bind("click", function(conn, originalEvent) {
//                alert(conn.getType());
                // conn.setType();
                deletingConnection = conn;
                conn.strokeStyle = 'rgba(0,255,0,0.7)';
                conn.repaint();

                var sourcePlanet = $("#" + conn.sourceId).attr("title");
                var destPlanet = $("#" + conn.targetId).attr("title");

                $("#myModalLabel2").text("Conferma eliminazione");
                $("#myModal2 .modal-body p").text("Vuoi cancellare la connessione tra il pianeta " + sourcePlanet + " e " + destPlanet + " ?");
                $('#myModal2').modal('show');
                
                



            });

            jsPlumb.bind("connectionDrag", function(connection) {
                console.log("Inizio a tracciare " + connection.id);
            });

            jsPlumb.bind("connectionDragStop", function(connection) {
                console.log("Connessione " + connection.id + " tracciata e posizionata");

            });

            jsPlumb.bind("connection", function(info, originalEvent) {
                //updateConnections(info.connection);
                currentConnection = info.connection;

                $("#connectionModalLabel").text("Scegli un colore della connessione");
                $('#connectionModal').modal('show');



//                alert(info.connection.id);

            });
        }
    };
    
    $("#delete-conn-confirm").click(function() {
                    
        var realSourceId = getRealIdFromFake(deletingConnection.sourceId);
        var realTargetId = getRealIdFromFake(deletingConnection.targetId);

        $.post("/connectionsServlet", {
            startPlanet: realSourceId,
            endPlanet: realTargetId,
            actionToDo: "delete"
        }).done(function(data) {
            alert("Connessione tra " + realSourceId + " e " + realTargetId + " eliminata");
        });

        jsPlumb.detach(deletingConnection);
        connections.splice(connections.indexOf(deletingConnection)); // rimuove dalla lista connessioni
    });
    
})();
